import { Badge, Menu } from 'antd'
import { RouterState } from 'connected-react-router'
import React, { useContext, useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import { TotalContext } from '../../anotherStore'
import { isAuth } from '../../helpers/auth'
import { itemCount } from '../../helpers/cart'
import { AppState } from '../../store/reducers'

const useActive = (currentPathName:string, pathName:string): string => {
  return currentPathName === pathName ? 'ant-menu-item-active': ''
}

const Navigation = () => {

  const router = useSelector<AppState, RouterState>(state=>state.router)
  // console.log(router.location)
  const isHome = useActive(router.location.pathname, "/")
  const isShop = useActive(router.location.pathname, "/shop")
  const isSignup = useActive(router.location.pathname, "/signup")
  const isSignin = useActive(router.location.pathname, "/signin")
  const isCart = useActive(router.location.pathname, "/cart")
  const isDashboard = useActive(router.location.pathname, dashboardUrl())
  const [count, setCount] = useContext(TotalContext)
  useEffect(()=>{
    setCount(itemCount())
  })
  function dashboardUrl() {
    let url = ''
    const auth = isAuth()
    if(auth) {
      const {
        user:
        {
          role
        }
      } = auth
      if (role === 0) {
        url = "/user/dashboard"
      }else {
        url = "/admin/dashboard"
      }
    }
    return url
  }
  return (
    <Menu mode="horizontal" selectable={false}>
      <Menu.Item className={isHome}>
        <Link to="/">首页</Link>
      </Menu.Item>
      <Menu.Item className={isShop}>
        <Link to="/shop">商城</Link>
      </Menu.Item>
      <Menu.Item className={isCart}>
        <Link to="/cart">购物车
        <Badge count={count} offset={[5,-10]} />
        </Link>
      </Menu.Item>
      {
        !isAuth() && <>
      <Menu.Item className={isSignup}>
        <Link to="/signup">注册</Link>
      </Menu.Item>
      <Menu.Item className={isSignin}>
        <Link to="/signin">登录</Link>
      </Menu.Item>
        </>
      }
            {
        isAuth() && 
      <Menu.Item className={isDashboard}>
        <Link to={dashboardUrl()}>dashboard</Link>
      </Menu.Item>
      }
    </Menu>
  )
}
export default Navigation